package yunjiao.javatutorials.guava.base.functional;

import com.google.common.base.Equivalence;
import com.google.common.collect.Sets;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 集合去重
 *
 * @author yangyunjiao
 */
public class CollectionDeduplication {

    public record Product(String id, String name, double price) {

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Product)) return false;
            Product product = (Product) o;
            return Objects.equals(id, product.id);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id);
        }

        @Override
        public String toString() {
            return String.format("Product{id='%s', name='%s', price=%.2f}", id, name, price);
        }
    }

    public static void main(String[] args) {
        List<Product> products = Arrays.asList(
                new Product("1", "Laptop", 999.99),
                new Product("2", "Mouse", 29.99),
                new Product("1", "Laptop Pro", 1299.99), // 相同ID，不同名称和价格
                new Product("3", "Keyboard", 79.99)
        );

        // 使用基于ID的等价关系来去重
        Equivalence<Product> idEquivalence =
                Equivalence.equals().onResultOf(Product::id);

        Set<Equivalence.Wrapper<Product>> uniqueProducts = Sets.newHashSet();
        for (Product product : products) {
            uniqueProducts.add(idEquivalence.wrap(product));
        }

        System.out.println("去重后的产品:");
        for (Equivalence.Wrapper<Product> wrapper : uniqueProducts) {
            System.out.println(wrapper.get());
        }
    }
}
